requireJS(['constant', 'site', 'handlebars', 'public'], function (Constant, site, Handlebars, Public) {
    Public.initProductSearch();
    Public.initApplyTerm();
    var url = {
        checkAccountList: "manager/checkAccountList.do",
        confirmationAccount: "manager/confirmationAccount.do",
        submitReceivablesReviewInit: "manager/submitReceivablesReviewInit.do",
        selectPaymentSort: "manager/selectPaymentSort.do",
        submitReceivables: "manager/submitReceivables.do",
        cancelPayment: "manager/cancelPayment.do",
        selectLoanMethodList: "manager/selectLoanMethodList.do",

        DailyInterestRate: "manager/DailyInterestRate.do"
    }

    //渲染搜索框的贷款方式
    site.send({
        url: url.selectLoanMethodList,
        callback: function (data) {
            data = JSON.parse(data);
            if (data.type == '1') {
                var source = $("#loanMethod_list_tpl").html();
                var template = Handlebars.compile(source);
                var list = data
                var html = template(list)
                $('#loan_way').append(html);
            }
        }
    })

    $("input[name='ch_id_all']").on('click', function () {
        var _checked = $("input[name='ch_id']")
        if ($(this).prop('checked')) {
            _checked.prop('checked', true)
        }
        else {
            _checked.prop('checked', false)
        }
    })

    var payId = "", order_id;
    var numed;
    var flun_type;
    var is_month_repayment_money;
    var is_comprehensive;
    var periods;
    var late_days;
    var is_penalty;
    var is_late_fee;
    var order_id;
    var product_id;
    var at_name;
    var repayment_way;
    var plan_payment_money;
    var loan_type;

    Constant.initHandlebars(Handlebars)
    //日期控件初始化
    $(".datepicker").datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
        pickerPosition: 'bottom',
    })

    var frontData = {
        pageNum: 1
    };

    var init = function () {
        site.send({
            url: url.checkAccountList,
            data: frontData,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == '1') {
                    var source = $("#checkAccount_content_tpl").html();
                    var template = Handlebars.compile(source);

                    var menuIndex = getAurlparam('h') || 0;
                    var thirdMenusIndex = getAurlparam('t') || 0;
                    var leftIndex = getAurlparam('i') || 0;
                    var storageContent = JSON.parse(localStorage.getItem('content'));
                    var obj = {
                        content: data,
                        fourthMenus: storageContent.menus[menuIndex].children[leftIndex].children[thirdMenusIndex].children || {}
                    }
                    var html = template(obj);
                    $("#checkAccount_content").html(html);
                    Public.record('t_order_public')

                    Constant.fn.initAllCheck();

                    if (data.content) {
                        $('.checkCount-page-container').createPager({
                            current: frontData.pageNum,
                            total: data.content.total,
                            pageSize: data.content.pageSize,
                            needInput: false,
                            backFn: function (current) {
                                frontData.pageNum = current;
                                init();
                            }
                        })
                        $('.result').html(data.content.total ? data.content.total : 0);
                    }

                    $(".operations").on('change', function () {
                        payId = $(this).data('payid');
                        order_id = $(this).data('id');
                        product_id = $(this).data('productid');
                        at_name = $(this).data('at_name')
                        if ($(this).val() == 'checkOrder') {
                            pjaxGo('finance/common/detail.html?product_id=' + product_id + '&order_id=' + order_id);
                        } else if ($(this).val() == 'confirmAccount') {
                            $(".getLoan_winBox").toggle();
                        }
                        else if ($(this).val() == 'changeAccount') {
                            $(".visitSelect").val('-1');
                            site.send({
                                url: url.selectPaymentSort,
                                callback: function (data) {
                                    data = JSON.parse(data);
                                    if (data.type == '1') {
                                        var sortList = data.content;
                                        var sortSource = $("#paymentSort_list_tpl").html();
                                        var sortTemplate = Handlebars.compile(sortSource);
                                        var sorthtml = sortTemplate(sortList);
                                        var ps_id = data.content[0].id;

                                        //日期控件初始化
                                        $(".datepicker").datepicker({
                                            format: 'yyyy-mm-dd',
                                            autoclose: true,
                                            pickerPosition: 'bottom',
                                        })

                                        site.send({
                                            url: url.submitReceivablesInit,
                                            data: {
                                                order_id: order_id
                                            },
                                            callback: function (data) {
                                                data = JSON.parse(data);
                                                if (data.type == '1') {
                                                    $("#putLoanRemarks").val("");
                                                    $('.putLoan_winBox').show();
                                                    var list = data.content;
                                                    var funPlan = data.content.funPlanlList[0]
                                                    funPlan.now_money = funPlan.is_month_repayment_money + funPlan.is_moth_repayment_rate + funPlan.is_comprehensive

                                                    var num;
                                                    var changeEle = {
                                                        penalty: true,
                                                        late_fee: true,
                                                        huaizhang: true,
                                                        qishu: true,
                                                        benjin: true
                                                    };
                                                    var depositReturn = -1;
                                                    var depositTF;

                                                    list.ps_id = ps_id;
                                                    list.loan_type = loan_type;
                                                    var sum = 0;
                                                    var sum_name = at_name.split('个')[0];
                                                    var depositOne, depositTwo, depositThere, depositFour;
                                                    $.each(list.depositMap, function (index, val) {
                                                        sum += val.deposit
                                                        if (val.type == 1) {
                                                            depositOne = val.deposit
                                                        }
                                                        if (val.type == 2) {
                                                            depositTwo = val.deposit
                                                        }
                                                        if (val.type == 3) {
                                                            depositThere = val.deposit
                                                        }
                                                        if (val.type == 4) {
                                                            depositFour = val.deposit
                                                        }
                                                    })
                                                    list.sum = sum;
                                                    list.depositOne = depositOne;
                                                    list.sum_name = sum_name;
                                                    if (list.funPlanlList.length) {
                                                        list.period_num = list.funPlanlList[0].periods.slice(1, -1);
                                                    }

                                                    if (ps_id == 5 || (ps_id == 1 && num == list.period_num)) {
                                                        changeEle.money = data.content.maps.sumMoney
                                                    } else {
                                                        changeEle.money = funPlan.now_money
                                                    }

                                                    if (depositReturn == 1) {
                                                        plan_payment_money = changeEle.money - sum
                                                    } else if (depositReturn == -1) {
                                                        plan_payment_money = changeEle.money
                                                    }

                                                    list.funPlan = funPlan
                                                    list.plan_payment_money = plan_payment_money;

                                                    var source = $("#putLoan_list_tpl").html();
                                                    var template = Handlebars.compile(source);
                                                    var html = template(list);
                                                    $("#putLoan_list").html(html);

                                                    /*var source2 = $("#special_putLoan_list_tpl").html();
                                                    var template2 = Handlebars.compile(source2);
                                                    var html2 = template2(list);*/

                                                    /*if (repayment_way != '4') {
                                                        $("#putLoan_list").html(html);
                                                    } else {
                                                        $("#putLoan_list").html(html2);
                                                        $("#qishu").html("本金（" + Constant.tplHelper.AMOUNT_FORMAT(list.applyMoney) + "）+【本金（" + Constant.tplHelper.AMOUNT_FORMAT(list.applyMoney) + "）*利息（" + list.interest / 100 + "）*天数（" + list.days + "）】");
                                                    }

                                                    if (repayment_way != '4') {
                                                        $("#paymentSort_list").html(sorthtml);
                                                    }*/
                                                    /*else{
                                                                                                $("#paymentSort_list").parents('td').html('按天计息');
                                                                                            }*/
                                                    //借款期限输入框填完后计算利息
                                                    $("#days").on('blur',function(){
                                                        if(parseInt($(this).val()) < parseInt(loandays)){
                                                            Constant.fn.Message("I","请输入大于借款日期的日期");
                                                            return;
                                                        };
                                                        $("#payedDays").text(loandays);
                                                        $("#paying").show();
                                                        $("#payed").show();
                                                        $("#payingDays").text(parseInt($(this).val()) - parseInt(loandays));
                                                        $("#daysApplyMoney").text(Constant.tplHelper.AMOUNT_FORMAT(apply_money));
                                                        $("#daysApplyInterest").text(Constant.tplHelper.AMOUNT_FORMAT((parseInt($(this).val()) - parseInt(loandays)) * apply_money * interest / 100));
                                                    })

                                                    $("#paymentSort_list").html(sorthtml);

                                                    $("#paymentSort_list").on('change', function () {
                                                        if ($(this).val() == '1') {
                                                            $("#deposit,#guarantee,#penalty,#late_fee_need,#beijin,#collectByDaysDetail,#collectByDays,.isBenJin").hide();
                                                            $(".comprehensive_fee").hide();
                                                            $("#transfer,#transerWay,#gathering,#come,#notbeijin,#qishu,.checkAccout,#thisTerm,#thisCollect,.collectDetail").show();
                                                            $("#zonghe").hide();
                                                            plan_payment_money = changeEle.money
                                                            $("#plan_payment_money").html('￥' + Constant.tplHelper.AMOUNT_FORMAT(plan_payment_money));
                                                        }
                                                        else if ($(this).val() == '2') {
                                                            $("#deposit,#guarantee,#penalty,#late_fee_need,#transfer,#transerWay,#beijin,#gathering,#come,#collectByDaysDetail,#collectByDays,.isBenJin").hide();
                                                            $(".comprehensive_fee").hide();
                                                            $("#notbeijin,#qishu,.checkAccout,#thisTerm,#thisCollect,.collectDetail").show();
                                                            $("#zonghe").hide();
                                                            plan_payment_money = changeEle.money
                                                            $("#plan_payment_money").html('￥' + Constant.tplHelper.AMOUNT_FORMAT(plan_payment_money));
                                                        }
                                                        else if ($(this).val() == '4') {
                                                            $("#deposit,#guarantee,#penalty,#beijin,#collectByDaysDetail,#collectByDays,.isBenJin").hide();
                                                            $(".comprehensive_fee").hide();
                                                            $("#late_fee_need,#transfer,#transerWay,#gathering,#come,#notbeijin,#qishu,.checkAccout,#thisTerm,#thisCollect,.collectDetail").show();
                                                            $("#zonghe").hide();
                                                            plan_payment_money = changeEle.money
                                                            $("#plan_payment_money").html('￥' + Constant.tplHelper.AMOUNT_FORMAT(plan_payment_money));
                                                        }
                                                        else if ($(this).val() == '5') {
                                                            $("#deposit,#guarantee,#penalty,#late_fee_need,#transfer,#transerWay,#come,#notbeijin,#beijin,.checkAccout,#thisTerm,#thisCollect,.collectDetail,.isBenJin").show();
                                                            $("#notbeijin,#qishu,#collectByDaysDetail,#collectByDays").hide();
                                                            $(".comprehensive_fee").hide();
                                                            $("#zonghe").hide();
                                                            changeEle._money = data.content.maps.sumMoney
                                                            if (depositReturn == 1) {
                                                                plan_payment_money = changeEle._money - sum
                                                            } else if (depositReturn == -1) {
                                                                plan_payment_money = changeEle._money
                                                            }
                                                            $("#plan_payment_money").html('￥' + Constant.tplHelper.AMOUNT_FORMAT(plan_payment_money));
                                                        }
                                                        else if ($(this).val() == '6') {

                                                        }
                                                        else if ($(this).val() == '7') {
                                                            $("#deposit,#guarantee,#penalty,#late_fee_need,#notbeijin,#beijin,#collectByDaysDetail,#collectByDays,.isBenJin").hide();
                                                            $("#transfer,#transerWay,#gathering,#come,#qishu,.checkAccout,#thisTerm,#thisCollect,.collectDetail").show();
                                                            $(".comprehensive_fee").show();
                                                            if (loan_type == '1') {
                                                                if (list.funMapLoan) {
                                                                    plan_payment_money = list.funMapLoan.is_moth_repayment_rate + list.funMapLoan.is_month_repayment_money + list.funMapLoan.is_comprehensive
                                                                    $(".periods").html(list.funMapLoan.periods);
                                                                    $(".plan_time").html(list.funMapLoan.repayment_time);
                                                                } else {
                                                                    plan_payment_money = 0;
                                                                }
                                                            } else {
                                                                plan_payment_money = list.funMap.is_moth_repayment_rate + list.funMap.is_month_repayment_money + list.funMap.is_comprehensive
                                                            }
                                                            $("#plan_payment_money").html('￥' + Constant.tplHelper.AMOUNT_FORMAT(plan_payment_money));
                                                            $("#zonghe").show();
                                                        }
                                                        else if ($(this).val() == '8') {
                                                            $("#thisTerm,#thisCollect,.collectDetail,#collectByDaysDetail,#collectByDays,.isBenJin").hide();
                                                        }
                                                        else if ($(this).val() == '9') {
                                                            $("#deposit,#guarantee,#penalty,#late_fee_need,#beijin,#collectByDaysDetail,#collectByDays").hide();
                                                            $(".comprehensive_fee").hide();
                                                            $("#thisCollect,#zonghe,#notbeijin,#beijin,#collectByDays").hide();
                                                            $("#collectByDays,#collectByDaysDetail,#come,.isBenJin").show();
                                                        }
                                                    })

                                                    $(".datepicker").datepicker();

                                                    //提交收款初始化处理，提交收款业务逻辑比较复杂
                                                    $("input[name='isLate']").on("click", function () {
                                                        if ($(this).val() == '1') {
                                                            $("#late_fee").show();
                                                        } else {
                                                            $("#late_fee").hide();
                                                            $("#late_fee_val").val(0);
                                                        }
                                                    })

                                                    $("input[name='isBenJin']").on("click", function () {
                                                        if ($(this).val() == '1') {
                                                            $("#benjin").show();
                                                        } else {
                                                            $("#benjin").hide();
                                                        }
                                                    })

                                                    $("#depositReturn").on('click', function () {
                                                        //先去除千分符
                                                        if ($(this).is(":checked")) {
                                                            depositReturn = 1;
                                                            plan_payment_money = (changeEle._money || changeEle.money) - sum
                                                            if (plan_payment_money < 0) {
                                                                plan_payment_money = changeEle._money
                                                                $("#plan_payment_money").html('￥' + Constant.tplHelper.AMOUNT_FORMAT(plan_payment_money));
                                                                depositReturn = -1;
                                                                depositTF = false;
                                                                Constant.fn.Message('I', '不能押金转本金');
                                                                return;
                                                            }
                                                        } else {
                                                            depositReturn = -1;
                                                            depositTF = false;
                                                            plan_payment_money = (changeEle._money || changeEle.money);
                                                            $("#plan_payment_money").html('￥' + Constant.tplHelper.AMOUNT_FORMAT(plan_payment_money));
                                                        }
                                                    })

                                                    $("#Depositforbreach").on('click', function () {
                                                        if ($(this).is(":checked")) {
                                                            //depositforbreach = 1
                                                            //depositTB = true
                                                            //penalty =sum || 123
                                                        } else {
                                                            //depositforbreach = -1
                                                            //depositTB = false
                                                        }
                                                    })
                                                }
                                                else {
                                                    Constant.fn.Message("F", data.msg)
                                                }
                                            }
                                        })
                                    }
                                    else {
                                        Constant.fn.Message("F", data.msg)
                                    }
                                }
                            })
                            /*else {
                                site.send({
                                    url: url.DailyInterestRate,
                                    data: {
                                        order_id: order_id,
                                        //loan_type: loan_type,
                                        type: '1',
                                        //days:'2018-10-12'
                                    },
                                    callback: function (data) {
                                        data = JSON.parse(data);
                                        if (data.type == '1') {
                                            //var list = JSON.parse(data);
                                            var source = $("#special_putLoan_list_tpl").html();
                                            var template = Handlebars.compile(source);
                                            //data.ps_id = '7';
                                            var html = template(data.content);
                                            $("#putLoan_list").html(html);
                                            $(".putLoan_winBox").show();

                                            $(".special_detail #qishu").html("本金（" + (data.content.applyMoney ? Constant.tplHelper.AMOUNT_FORMAT(data.content.applyMoney) : '--') + "）+【本金（" + (data.content.applyMoney ? Constant.tplHelper.AMOUNT_FORMAT(data.content.applyMoney) : '--') + "）*利息（" + (data.content.interest ? data.content.interest / 100 : '--') + "）*天数（" + (data.content.days ? data.content.days : '--') + "）】");
                                            $(".special_gathering #plan_payment_money").html('￥' + (data.content.sumMoney ? Constant.tplHelper.AMOUNT_FORMAT(data.content.sumMoney) : '--'));
                                            $('.day').html(data.content.days ? data.content.days : '--');


                                            $(".datepicker").datepicker();
                                            $(".special_come .real_time").on("change", function () {
                                                site.send({
                                                    url: url.DailyInterestRate,
                                                    data: {
                                                        order_id: order_id,
                                                        //loan_type: loan_type,
                                                        type: '2',
                                                        days: $(this).val()
                                                    },
                                                    callback: function (data) {
                                                        data = JSON.parse(data);
                                                        if (data.type == 1) {
                                                            $(".special_detail #qishu").html("本金（" + (data.content.applyMoney ? Constant.tplHelper.AMOUNT_FORMAT(data.content.applyMoney) : '--') + "）+【本金（" + (data.content.applyMoney ? Constant.tplHelper.AMOUNT_FORMAT(data.content.applyMoney) : '--') + "）*利息（" + (data.content.interest ? data.content.interest / 100 : '--') + "）*天数（" + (data.content.days ? data.content.days : '--') + "）】");
                                                            $(".special_gathering #plan_payment_money").html('￥' + (data.content.sumMoney ? Constant.tplHelper.AMOUNT_FORMAT(data.content.sumMoney) : '--'));
                                                            $('.day').html(data.content.days ? data.content.days : '--');
                                                        } else {

                                                        }
                                                    }
                                                })
                                            })

                                            $("#special_paymentSort_list").on("change", function () {
                                                if ($(this).val() == '1') {
                                                    $('.special_term,.composive_detail,#come,.composive_gathering').show();
                                                    $('.special_come,.special_detail,.days,.special_gathering').hide();
                                                } else {
                                                    $('.special_term,.composive_detail,#come,.composive_gathering').hide();
                                                    $('.special_come,.special_detail,.days,.special_gathering').show();
                                                }
                                            })
                                        }
                                    }
                                })
                            }*/
                        }

                        else if ($(this).val() == 'cancelPayment') {
                            $(".canPay_winBox").toggle();
                        }
                        $(this).val(-1);
                    })
                }
            }
        })
    }
    init();

    $("#toOrder-select").on('change', function () {
        var obj = $(this).find("option:selected");
        if (obj.val() == '1') {
            $("#main-content").hide();
            $("#toOrder-content").show();
        }
        //if()
    })


    //确认收款
    $("#sureGetLoan").on("click", function () {
        site.send({
            url: url.confirmationAccount,
            data: {
                payId: payId
            },
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == '1') {
                    $(".getLoan_winBox").toggle();
                    Constant.fn.Message("T", data.msg);
                    pjaxReload();
                } else {
                    Constant.fn.Message("F", data.msg);
                }
            }
        })
    })

    //提交收款确认按钮
    $("#surePutLoan").on('click', function () {
        var pmType = $("input[name='isCheck']:checked").val();
        var daytype = $("input[name='isBenJin']:checked").val();
        //var plan_payment_money = $("#plan_payment_money").data('plan_payment_money');
        var data = {
            oid: order_id,
            ps_id: $("#paymentSort_list").val(),
            plan_payment_money: plan_payment_money,
            //real_payment_money: $("#real_payment_money").val(),
            //receipt_number: $("#transferMan").val(),
            //transfer_mode: $("#trans").val(),
            //real_time: $(".real_time").val(),
            fund_plan_id: $("#fund_plan_id").val(),
            //penalty: $("#penalty_val").val() ? $("#penalty_val").val() : 0,
            //late_fee: $("#late_fee_val").val() ? $("#late_fee_val").val() : 0,
            //depositReturn:
            status: 1,
            late_days: late_days,
            r_penalty: is_penalty,
            r_late_fee: is_late_fee,
            is_month_repayment_money: is_month_repayment_money,
            remarks: $("#putLoanRemarks").val(),
        };
        if ($("#real_payment_money").parents('tr').css('display') != 'none') {
            data.real_payment_money = $("#real_payment_money").val()
        }

        if ($("#transferMan").parents('tr').css('display') != 'none') {
            data.receipt_number = $("#transferMan").val()
        }

        if ($("#trans").parents('tr').css('display') != 'none') {
            data.transfer_mode = $("#trans").val()
        }

        if ($(".real_time").parents('tr').css('display') != 'none') {
            data.real_time = $(".real_time").val()
        }

        $.each($(".real_time"), function (i, e) {
            if ($(e).parents('tr').css('display') != 'none' && $(e).val()) {
                data.real_time = $(e).val()
            }
        })


        if ($("#penalty_val").parents('tr').css('display') != 'none') {
            data.penalty = $("#penalty_val").val()
        }

        if ($("#late_fee_val").parents('tr').css('display') != 'none') {
            data.late_fee = $("#late_fee_val").val()
        }

        if ($("#depositReturn").parents('tr').css('display') != 'none' && $("#depositReturn").is(":checked")) {
            data.depositReturn = 1;
        }

        if ($("#Depositforbreach").parents('tr').css('display') != 'none' && $("#Depositforbreach").is(":checked")) {
            data.Depositforbreach = 2;
        }
        if (!pmType && $('.checkAccout').css('display') != 'none') {
            Constant.fn.Message("I", "请选择是否需要复核到账");
            return;
        }
        if (pmType) {
            data.pmtype = pmType;
        }
        if ($("#gathering").css('display') != 'none' && !$("#real_payment_money").val()) {
            Constant.fn.Message("I", "请填写实际收款");
            return;
        }
        if ($("#come").css('display') != 'none' && !$("#come").find(".real_time").val()) {
            Constant.fn.Message("I", "请填写到账日期");
            return;
        }
        if($("#paymentSort_list").val() === '9' && !daytype){
            Constant.fn.Message("I", "请选择是否收取本金");
            return;
        }
        if(daytype){
            data.daytype = daytype;
        }
        if($("#days").val()){
            data.days = $("#days").val();
        }
        site.send({
            url: url.submitReceivables,
            data: data,
            callback: function (data) {
                data = JSON.parse(data);
                if (data.type == '1') {
                    Constant.fn.Message("T", data.msg);
                    $(".putLoan_winBox").hide();
                    init()
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            },
        })
    })

    //取消收款
    $('.sureCanPay').on('click', function () {
        site.send({
            url: url.cancelPayment,
            data: {
                pay_id: payId,
                oid: order_id
            }, callback: function (data) {
                data = JSON.parse(data);
                if (data.type == '1') {
                    $('.canPay_winBox').toggle();
                    Constant.fn.Message("T", data.msg);
                    pjaxReload();
                }
                else {
                    Constant.fn.Message("F", data.msg)
                }
            },
        })
    })

    //批量操作

    $(".backArr ").on('change', function () {
        payId = "";
        var selected = $(this).find("option:selected");
        $(this).find("option:first").prop("selected", false).prop("selected", true);
        $("input[name='ch_id']:checked").each(function (index, item) {
            payId = payId + $(item).val() + ","
        })
        payId = payId.substring(0, payId.length - 1)
        if (selected.val() == '确认到账') {
            //删除产品
            if (!payId) {
                Constant.fn.Message('I', "未选择要确认到账的订单")
                return;
            }
            $('.getLoan_winBox').toggle();
        }
    })

    $("#sousuo").click(function () {
        frontData = {
            pageNum: 1
        }
        if ($("#start_time").val()) {
            frontData.start_time = $("#start_time").val();
        }
        if ($("#end_time").val()) {
            frontData.end_time = $("#end_time").val();
        }
        if ($(".headData_select").val()) {
            frontData.atId = $(".headData_select").val();
        }
        if ($("#time_type").val()) {
            frontData.time_type = $("#time_type").val();
        }
        if ($("#seleNames").val()) {
            frontData.type = $("#seleNames").val();
        }
        if ($("#inputNames").val()) {
            frontData.keyword = $("#inputNames").val();
        }
        if ($("#loan_way").val()) {
            frontData.loan_way = $("#loan_way").val();
        }
        if ($("#product_choose_list").val()) {
            frontData.product_id = $("#product_choose_list").val()
        }
        /*if($(".role_select").val()){
            frontData.admin_id = $(".role_select").val();
        }*/
        init();
    })


})